class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses];
        List<List<Integer>> edge = new ArrayList<>(); 
        for(int i=0;i<numCourses;i++){
            edge.add(new ArrayList<>());
        }
        for(int i=0;i<prerequisites.length;i++){
            int a=prerequisites[i][0];
            int b=prerequisites[i][1];
            edge.get(b).add(a);
            in[a]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for(int i=0;i<numCourses;i++){
            if(in[i]==0) q.add(i);
        }
        int[] ret=new int[numCourses];
        int index=0;
        while(!q.isEmpty()){
            int t=q.poll();
            ret[index++]=t;
            for(int x:edge.get(t)){
                in[x]--;
                if(in[x]==0) q.add(x);
            }
        }
        if(index==numCourses) return ret;
        return new int[0];
    }
}